/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ConvertorView.java
 *
 * Created on 29-Mar-2012, 10:59:20
 */
package uk.ac.liv.maxquantmzquantmlconvertor.gui;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileNameExtensionFilter;
import uk.ac.liv.maxquantmzquantmlconvertor.MaxquantMzquantmlConvertor;

/**
 *
 * @author Da Qi
 */
public class ConvertorView extends javax.swing.JFrame {

    private File currentDirectory;

    /**
     * Creates new form ConvertorView
     */
    public ConvertorView() {

        //... Setting standard look and feel ...//
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (ClassNotFoundException ex) {
            System.out.println(ex.getStackTrace());
        }
        catch (InstantiationException ex) {
            System.out.println(ex.getStackTrace());
        }
        catch (IllegalAccessException ex) {
            System.out.println(ex.getStackTrace());
        }
        catch (UnsupportedLookAndFeelException ex) {
            System.out.println(ex.getStackTrace());
        }

        // Get the size of the screen
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

        // Determine the new location of the window
        int w = this.getSize().width;
        int h = this.getSize().height;
        int x = (dim.width - w) / 4;
        int y = (dim.height - h) / 4;

        // Move the window
        this.setLocation(x, y);

        initComponents();
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fileConvertorPanel = new javax.swing.JPanel();
        fileSelPanel = new javax.swing.JPanel();
        jbSelFold = new javax.swing.JButton();
        selFolder = new javax.swing.JTextField();
        jbReset = new javax.swing.JButton();
        jbConvert = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        convRes = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("MaxQuant to MzQuantML Convertor");
        setResizable(false);

        fileConvertorPanel.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        fileConvertorPanel.setEnabled(false);
        fileConvertorPanel.setPreferredSize(new java.awt.Dimension(774, 340));

        fileSelPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jbSelFold.setText("Select folder ...");
        jbSelFold.setToolTipText("");
        jbSelFold.setActionCommand("");
        jbSelFold.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbSelFoldActionPerformed(evt);
            }
        });

        jbReset.setText("Reset");

        jbConvert.setText("Convert");
        jbConvert.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbConvertActionPerformed(evt);
            }
        });

        jLabel1.setForeground(new java.awt.Color(204, 0, 0));
        jLabel1.setText("<html>\nPlease select the folder containing all the required maxQuant output files as follows:<br>\nexperimentalDesignTemplate.txt, evidence.txt, parameters.txt, peptides.txt, proteinGroups.txt\n</html>");

        javax.swing.GroupLayout fileSelPanelLayout = new javax.swing.GroupLayout(fileSelPanel);
        fileSelPanel.setLayout(fileSelPanelLayout);
        fileSelPanelLayout.setHorizontalGroup(
            fileSelPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, fileSelPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(fileSelPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 750, Short.MAX_VALUE)
                    .addGroup(fileSelPanelLayout.createSequentialGroup()
                        .addComponent(selFolder, javax.swing.GroupLayout.DEFAULT_SIZE, 635, Short.MAX_VALUE)
                        .addGap(8, 8, 8)
                        .addComponent(jbSelFold))
                    .addGroup(fileSelPanelLayout.createSequentialGroup()
                        .addComponent(jbReset)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jbConvert)))
                .addContainerGap())
        );
        fileSelPanelLayout.setVerticalGroup(
            fileSelPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(fileSelPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(fileSelPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(selFolder, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbSelFold))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(fileSelPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbConvert, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbReset, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(27, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Conversion results"));

        convRes.setColumns(20);
        convRes.setRows(5);
        convRes.setWrapStyleWord(true);
        jScrollPane2.setViewportView(convRes);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 762, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 14, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout fileConvertorPanelLayout = new javax.swing.GroupLayout(fileConvertorPanel);
        fileConvertorPanel.setLayout(fileConvertorPanelLayout);
        fileConvertorPanelLayout.setHorizontalGroup(
            fileConvertorPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(fileSelPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        fileConvertorPanelLayout.setVerticalGroup(
            fileConvertorPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(fileConvertorPanelLayout.createSequentialGroup()
                .addComponent(fileSelPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 774, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(fileConvertorPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 0, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 355, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(fileConvertorPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 0, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbSelFoldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSelFoldActionPerformed
        JFileChooser fileChooser = new javax.swing.JFileChooser("user.home");
        fileChooser.setDialogTitle("Select the maxQuant files folder.");
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fileChooser.setCurrentDirectory(currentDirectory);

        int returnVal = fileChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            this.selFolder.setText(file.getAbsolutePath());
            currentDirectory = file.getParentFile();
        }
    }//GEN-LAST:event_jbSelFoldActionPerformed

    private void jbConvertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbConvertActionPerformed
        if (selFolder.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this.fileConvertorPanel, "No file folder is selected, nothing to convert!");
        }
        else {
            JFileChooser fileChooser = new javax.swing.JFileChooser();
            fileChooser.setDialogTitle("Save the MzQuantML file");
            fileChooser.setCurrentDirectory(currentDirectory);

            //... Applying file extension filters ...//
            FileNameExtensionFilter filter = new FileNameExtensionFilter("MzQuantML (*.mzq)", "mzq");
            fileChooser.setFileFilter(filter);

            int returnVal = fileChooser.showSaveDialog(this);
            //String outputFn = " ";
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                try {
                    File file = fileChooser.getSelectedFile();
                    String outputFn = file.getAbsolutePath().endsWith("mzq") ? file.getAbsolutePath() : file.getAbsolutePath() + ".mzq";

                    this.convRes.setLineWrap(true);
                    this.convRes.setText("Start converting......\n");
                    this.convRes.update(this.convRes.getGraphics());

                    //MaxquantMzquantmlConvertor.convert(selFolder.getText(), outputFn);
                    MaxquantMzquantmlConvertor maxCon = new MaxquantMzquantmlConvertor(selFolder.getText());

                    maxCon.convert(outputFn);

                    this.convRes.append("Conversion completed:\n");
                    this.convRes.update(this.convRes.getGraphics());
                    String out = "The mzQuantML file is stored in\n" + outputFn;
                    this.convRes.append(out);
                }
                catch (IOException ex) {
                    Logger.getLogger(ConvertorView.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }//GEN-LAST:event_jbConvertActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel.
         * For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }
        catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ConvertorView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ConvertorView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ConvertorView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ConvertorView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ConvertorView().setVisible(true);
            }

        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea convRes;
    private javax.swing.JPanel fileConvertorPanel;
    private javax.swing.JPanel fileSelPanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jbConvert;
    private javax.swing.JButton jbReset;
    private javax.swing.JButton jbSelFold;
    private javax.swing.JTextField selFolder;
    // End of variables declaration//GEN-END:variables
}
